//界面加载获取token
const userMsg = JSON.parse(localStorage.getItem("userMsg")) || [];

const token = userMsg.token;

//界面加载渲染购物车列表
async function getShopCart() {
  let { data: res } = await axios.get(
    "http://cba.itlike.com/public/index.php?s=/api/cart/list",
    {
      headers: {
        "Access-Token": token,
        platform: "H5",
      },
    }
  );
  document.querySelector(".cartMain").innerHTML = res.data.list
    .map((item) => {
      console.log(item);
      const {
        goods: { goods_name, goods_price_max, goods_image, goods_id },
        goods_num,
      } = item;
      console.log(item);
      return `
      <div class="cartMain1" data-id=${goods_id}>
        <input type="checkbox" class="checkbox" />
        <input type="hidden" class="hiddenVal">
        <div class="cartMsg">
          <img src="${goods_image}" alt="" />
          <div class="cartDetail2">
            <h3>${goods_name}</h3>
            <div class="cartDCont">
              <p class="commonMoney">￥<span class="singlePrice">${goods_price_max}</span></p>
              <div class="count">
                <button class="decrease">-</button>
                <input type="text" class="goodsSum" value=${goods_num} />
                <button class="increase">+</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    `;
    })
    .join("");

  //获取商品数量
  let goodCount = document.querySelectorAll(".count");
  goodCount.forEach((item) => {
    item.addEventListener("click", function (e) {
      let target = e.target;

      if (target.className == "decrease") {
        const inp = target.nextElementSibling;
        const hidden =
          target.parentNode.parentNode.parentNode.parentNode
            .previousElementSibling;
        const checkBox =
          target.parentNode.parentNode.parentNode.parentNode
            .previousElementSibling.previousElementSibling;
        const singleVal =
          +target.parentNode.previousElementSibling.querySelector(
            ".singlePrice"
          ).innerHTML;
        if (inp.value == 1) {
          return alert("不能再减了~");
        } else {
          inp.value--;
          hidden.value = singleVal * inp.value;
          toHiddenMoney(checkBox);
        }
      }
      if (target.className == "increase") {
        const inp = target.previousElementSibling;
        const hidden =
          target.parentNode.parentNode.parentNode.parentNode
            .previousElementSibling;
        const checkBox =
          target.parentNode.parentNode.parentNode.parentNode
            .previousElementSibling.previousElementSibling;
        const singleVal =
          +target.parentNode.previousElementSibling.querySelector(
            ".singlePrice"
          ).innerHTML;
        inp.value++;
        hidden.value = singleVal * inp.value;
        toHiddenMoney(checkBox);
      }
    });
  });

  //点击全选复选框=>所有复选框都被选中
  const checkbox = document.querySelector("#checkbox");
  const box = document.querySelectorAll(".checkbox");
  checkbox.addEventListener("click", function () {
    for (let i = 0; i < box.length; i++) {
      box[i].checked = checkbox.checked;
      toHiddenMoney(box[i]);
    }
  });

  //点击子复选框给父复选框添加状态
  for (let i = 0; i < box.length; i++) {
    box[i].addEventListener("click", function () {
      checkbox.checked = Array.from(box).every((item) => item.checked);
      toHiddenMoney(box[i]);
    });
  }

  const checkboxEl = document.querySelectorAll(".checkbox");

  //点击编辑
  const edit = document.querySelector(".edit");
  let flag = true;
  const editHtml = edit.innerHTML;
  const account = document.querySelector(".account");
  const cancel = document.querySelector(".cancel");
  let newCheckbox = [];
  edit.addEventListener("click", function () {
    let editHtml2 = `<span style="color: red; font-size: 3.7333vw">完成</span>`;
    console.log(flag);
    if (flag) {
      this.innerHTML = editHtml2;
      account.style.display = "none";
      cancel.style.display = "block";
    } else {
      this.innerHTML = editHtml;
      account.style.display = "block";
      cancel.style.display = "none";
    }
    flag = !flag;
  });

  //点击删除按钮
  let goodsIdArr = [];
  cancel.addEventListener("click", function () {
    //获取被选中的复选框
    newCheckbox = [...checkboxEl].filter((item) => item.checked == true);
    newCheckbox.forEach((item) => {
      item.parentNode.remove();
      goodsIdArr.push(+item.parentNode.dataset.id);
    });
    edit.innerHTML = editHtml;
    account.style.display = "block";
    cancel.style.display = "none";
    document.querySelector(".totalPrice").innerHTML = +0.0;
    cancelCartGood(goodsIdArr, token);
    // getShopCart();
  });
}
getShopCart();

//删除购物车商品
async function cancelCartGood(godsId, token) {
  let { data: res } = await axios.post(
    "http://cba.itlike.com/public/index.php?s=/api/cart/clear",
    JSON.stringify({
      cartIds: godsId,
    }),
    {
      headers: {
        "Access-Token": token,
        platform: "H5",
      },
    }
  );
  console.log(res);
}

//更新删除后的商品
// async function getCancledGoodsList() {
//   let res = await axios.get(
//     "http://cba.itlike.com/public/index.php?s=/api/cart/list",
//     {
//       headers: {
//         "Access-Token": token,
//         platform: "H5",
//       },
//     }
//   );
//   console.log(res)
// }

//封装更新购物车商品
async function getGoodCart() {
  //let {data: res} = await axios.
}

//点击子复选框将金额赋值给隐藏input
function toHiddenMoney(el) {
  const parent = el.parentNode;

  //获取单价元素
  const singlePrice = +parent.querySelector(".singlePrice").innerHTML;

  //获取商品数量
  const goodsSum = +parent.querySelector(".goodsSum").value;

  //商品总价为
  let totalPriceVal = (singlePrice * goodsSum).toFixed(2);

  //赋值给hidden input框
  el.nextElementSibling.value = totalPriceVal;

  getTotalMoney();
}

//遍历隐藏input的值获取金额
function getHiddenMoney() {
  let str = 0;
  Array.from(checkboxEl).forEach((item) => {
    if (item.checked == true) {
      str += +item.nextElementSibling.value;
    }
  });
  document.querySelector(".totalPrice").innerHTML = str.toFixed(2);
}

//封装获取复选框的状态来计算总费用
function getTotalMoney() {
  let checkboxNew = document.querySelectorAll(".checkbox");
  arr = [];
  for (let i = 0; i < checkboxNew.length; i++) {
    if (checkboxNew[i].checked == true) {
      arr.push(+checkboxNew[i].nextElementSibling.value);
      getTotalPrice(arr);
    } else {
      getTotalPrice(arr);
    }
  }
}

//计算总价
function getTotalPrice(arr) {
  document.querySelector(".totalPrice").innerHTML = arr
    .reduce((prev, cur) => prev + cur, 0)
    .toFixed(2);
}
